<template>
  <div align="center" style="height: 800px;width: 100%;background: white">
    <div align="center">
      <table  width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
          <td><div  style="margin-left: 100px;float: left"><img v-on:click="indexLayout" src="../../assets/logo.jpg" height="120px" width="250px" ></div>
          </td>
        </tr>
      </table>
    </div>
    <div style="background: white;width: 1000px;height: 550px;margin-top: 50px;border-radius:20px; box-shadow:1px 2px 3px 4px #ccc"  >
      <div style="float: left;margin-left:6%;margin-top: 6%">
      <img height="400px" width="450px" src="../../assets/loginpage.png">
      </div>
      <div class="login_box">
        <p style="font-family: 黑体;font-size: 40px ;width: 150px;height: 60px">登录</p>
        <div style="float: left;margin-left: 80px;margin-top:-15px">
          <p >账号：</p>
          <p style="margin-top: 45px">密码：</p>
          <p style="margin-top: 32px">验证码：</p>
        </div>
        <div style="float: left">
          <el-form ref="LoginFormRef" :model="loginForm" label-width="0" :rules="LoginFormRules"class="login_form" >
            <el-form-item prop="id">
              <el-input placeholder="请输入手机号" v-model.number="loginForm.id" prefix-icon="el-icon-user" style="width: 200px"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input placeholder="请输入密码" v-model="loginForm.password" prefix-icon="el-icon-lock" type="password" style="width: 200px"></el-input>
            </el-form-item>
            <el-form-item prop="code">
              <el-input  placeholder="请输入验证码" id="code" style="width: 117px" v-model="loginForm.code"></el-input>
              <input type="button" id="verification" @click="createCode()"/>
            </el-form-item>
            <el-form-item align="center" style="height: 20px">
              <el-button type="danger" style="width: 100px" @click="login">登录</el-button>
            </el-form-item>

          </el-form>
        </div>
      </div>
      <div class="box1">
        <el-link  v-on:click="retPassword">忘记密码</el-link>|<el-link v-on:click="register" >免费注册</el-link>|<el-link v-on:click="managerLogin" >管理</el-link>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: "UserLogin",
    data() {
      return {
        code:'',
        loginForm:{id:null,password:'',code:''},
        // 正则表达式的相关校验
        LoginFormRules: {
          id: [{required: true, message: '请输入手机号', trigger: 'blur'},
               {type:'number',message: '请输入数字', trigger: 'blur'}],
          password: [{required: true, message: '请输入密码', trigger: 'blur'}],
          code:[{required: true, message: '请输入验证码', trigger: 'blur'}]
        }
      }
    },
    mounted() {
      this.createCode();
    },
    methods: {
      createCode() {
        this.verification = '';
        var codeLength = 4;//验证码的长度
        var checkCode = document.getElementById("verification");
        var random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
          'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');//随机数
        for (var i = 0; i < codeLength; i++) {//循环操作
          var index = Math.floor(Math.random() * 36);//取得随机数的索引（0~35）
          this.verification += random[index];//根据索引取得随机数加到code上
        }
        checkCode.value = this.verification;//把code值赋给验证码
      },
      register(){
        this.$router.push({path:"/UserRegister"});
      },
      managerLogin(){
        this.$router.push({path:"/adminLogin"});
      },
      indexLayout(){
        this.$router.push({path:"/IndexLayout"});
      },
      retPassword(){
        this.$router.push({path:"/Step1"});
      },
      login() {
        var inputCode = document.getElementById("code").value.toUpperCase(); //取得输入的验证码并转化为大写
        var judge = 0;
        if (inputCode.length <= 0) { //若输入的验证码长度为0
          alert("请输入验证码！"); //则弹出请输入验证码
        } else if (inputCode != this.verification) { //若输入的验证码与产生的验证码不一致时
          alert("验证码输入错误！@_@"); //则弹出验证码输入错误
          this.createCode();//刷新验证码
          document.getElementById("input").value = "";//清空文本框
        }
          //首先是校验如果正则的校验通过 -->> 执行数据传输
          this.$refs['LoginFormRef'].validate(async (valid) => {
            if (valid) {
              console.log(1);
              //执行数据的交互过程 --即对服务端对应接口进行访问
              const {data: res} = await this.$http.post('http://localhost:8888/userLogin',
                {id: this.loginForm.id, password: this.loginForm.password},
                {emulateJSON: true});
              if (res.code === 200) {
                // alert('登录成功！')
                // this.$message({
                //   message: res.msg,
                //   type: 'success',
                // });
                this.$message({
                  showClose: true,
                  message: '登录成功！',
                  type: 'success'
                });
                console.log(res.data);
                //全局存储登录状态（后期可使用Vuex进行状态管理）
                window.sessionStorage.setItem('loginState', res.data);
                //全局存储用户信息
                window.sessionStorage.setItem('id', res.data.id);
                window.sessionStorage.setItem('password', res.data.password);
                window.sessionStorage.setItem('userName', res.data.userName);
                window.sessionStorage.setItem('phone', res.data.phone);
                window.sessionStorage.setItem('sex', res.data.sex);
                window.sessionStorage.setItem('email', res.data.email);
                window.sessionStorage.setItem('age', res.data.age);
                window.sessionStorage.setItem('address', res.data.address);
                window.sessionStorage.setItem('introduction', res.data.introduction);
                window.sessionStorage.setItem('img', res.data.img);

                //跳转主页
                this.$router.push({path: '/IndexLayout', query: {userName: res.data.userName}});
              } else {
                // alert('登陆失败，请重新登录！')
                // this.$message({
                //   message: res.msg,
                //   type: 'error'
                // })
                this.$message({
                  showClose: true,
                  message: '登陆失败，请重新登录！',
                  type: 'error'
                });
              }
            } else {
              return false
            }
          })
        }
      }

  }
</script>

<style lang="less" scoped>
  .ti{font-size: 70px;
    color: black;
    font-family: 黑体;}

  .login_form {
    float: left;
    position: absolute;
    bottom: 0;
    width: 50%;
    height: 70%;
    padding: 20px;
    box-sizing: border-box;
  }

  .login_box {
    /*background: rgba(117, 66, 75, 0.3);*/
    float: left;
    margin-top: 170px;
    margin-left: 100px;
    width: 450px;
    height: 350px;
    border-radius: 3px;
    position: absolute;
    left: 60%;
    top: 30%;
    transform: translate(-50%, -50%);
    /*border-color: black;*/
    /*border: solid;*/
  }

  .box1 {
    float: left;
    margin-top: 400px;
    margin-left: 190px;
    /*border-color: black;*/
    /*border: solid;*/
  }
  #verification
  {
    font-family:Arial;
    font-style:italic;
    font-weight:bold;
    border:0;
    letter-spacing:2px;
    color:blue;
  }
</style>

